package edu.jamestang.yeb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.jamestang.yeb.entity.Menu;
import edu.jamestang.yeb.entity.MenuRole;
import edu.jamestang.yeb.entity.Role;
import edu.jamestang.yeb.service.MenuRoleService;
import edu.jamestang.yeb.service.MenuService;
import edu.jamestang.yeb.service.RoleService;
import edu.jamestang.yeb.util.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JamesTang
 * @date 2021/12/15 11:05
 */
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    private static final String ROLE_PREFIX = "ROLE_";

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuRoleService menuRoleService;

    @ApiOperation(value = "Get all role")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation(value = "Add Role")
    @PostMapping("/")
    public Resp addRole(@RequestBody Role role){

        if(!role.getName().startsWith(ROLE_PREFIX)){
            role.setName(ROLE_PREFIX+role.getName());
        }
        if(roleService.save(role)){
            return Resp.success("Add success");
        }
        return Resp.error("Add error");
    }

    @ApiOperation(value = "Delete Role")
    @DeleteMapping("/role/{id}")
    public Resp deleteRole(@PathVariable Integer id){

        if(roleService.removeById(id)){
            return Resp.success("Delete success");
        }
        return Resp.error("Delete error");
    }

    @ApiOperation(value = "Get all menu")
    @GetMapping("/menus")
    public List<Menu> getAllMenus(){

        return menuService.getAllMenus();
    }

    @ApiOperation(value = "Get menu id by role id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        return menuRoleService.list(
                new QueryWrapper<MenuRole>().eq("rid",rid))
                .stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value = "Update role menu")
    @PutMapping("/")
    public Resp updateMenuRole(Integer rid, Integer[] mIds){
        return menuRoleService.updateMenuRole(rid, mIds);
    }
}
